package net.cookiefarmers.seedswap

import org.springframework.dao.DataIntegrityViolationException

class UserController {
	public static int loginAttempts = 3;

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

/*****************************************************************************************************************************************************/
  def scaffold = User
  
  def login = {

	if(session.user ){
	
		redirect(controller:"user", action:"list")
		return false
	}	
   }
  
 /* def beforeInterceptor = [action:this.&auth, except:["index", "login", "show"]]

  def auth() {
    if(session.user) {
      redirect(controller:"user", action:"list")
      return false
    }
  }*/

  def authenticate = {
    def user = User.findByLoginAndPassword(params.login, params.password)
	if(user)
	if(user.accountStatus == "locked"){
		flash.message = "Your account has been locked due to too many wrong attempts. Contact your administrator for further instructions"
		redirect(action:"login")
		return false
	}
    if(user){
      session.user = user
      flash.message = "Hello ${user.name}!"
	if(user.login != "admin")
      		redirect(controller:"user", action:"list") 
	else	
		redirect(controller:"admin", action:"list")    
    }else{
	loginAttempts--;
	if(loginAttempts == 0){
		flash.message = "Your account has been locked. Contact your administrator for further instructions"
	
		User.executeUpdate("update User u set u.accountStatus='locked' where u.login=?",[params.login])
		redirect(action:"login")
		loginAttempts = 3;
		return
	}
      flash.message = "Sorry, ${params.login}. Either your login name or password does not much our records. You may attempt "+loginAttempts+" more logins before your account locks.";
      redirect(action:"login")
	
	
    }
  }
  

  def logout = {
    flash.message = "Goodbye ${session.user.name}"
    session.user = null
    redirect(controller:"user", action:"login")      
  } 


    def index() {
        redirect(action: "list", params: params)
    }

    def list() {
	if(!session.user){
		flash.message = "You need to log in in order to access this page"
		redirect(controller:"user", action:"login")
		return true
	}
	if(session.user && session.user.login == "admin")
		redirect(controller:"admin", action:"list")
     /*   params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [userInstanceList: User.list(params), userInstanceTotal: User.count()]*/
    }

/********************************************************************************************************************************************************/

    def create() {

        [userInstance: new User(params)]
    }

    def save() {
	params['accountStatus'] = "unlocked"
        def userInstance = new User(params)
        if (!userInstance.save(flush: true)) {
            render(view: "create", model: [userInstance: userInstance])
            return
        }

		flash.message = message(code: 'default.created.message', args: [message(code: 'user.label', default: 'User'), userInstance.id])
        redirect(action: "show", id: userInstance.id)
    }

    def show() {
        def userInstance = User.get(params.id)
        if (!userInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])
            redirect(action: "list")
            return
        }

        [userInstance: userInstance]
    }

    def edit() {
        def userInstance = User.get(params.id)
        if (!userInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])
            redirect(action: "list")
            return
        }

        [userInstance: userInstance]
    }

    def update() {
        def userInstance = User.get(params.id)
        if (!userInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])
            redirect(action: "list")
            return
        }

        if (params.version) {
            def version = params.version.toLong()
            if (userInstance.version > version) {
                userInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'user.label', default: 'User')] as Object[],
                          "Another user has updated this User while you were editing")
                render(view: "edit", model: [userInstance: userInstance])
                return
            }
        }

        userInstance.properties = params

        if (!userInstance.save(flush: true)) {
            render(view: "edit", model: [userInstance: userInstance])
            return
        }

		flash.message = message(code: 'default.updated.message', args: [message(code: 'user.label', default: 'User'), userInstance.id])
        redirect(action: "show", id: userInstance.id)
    }

    def delete() {
        def userInstance = User.get(params.id)
        if (!userInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])
            redirect(action: "list")
            return
        }

        try {
            userInstance.delete(flush: true)
			flash.message = message(code: 'default.deleted.message', args: [message(code: 'user.label', default: 'User'), params.id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
			flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'user.label', default: 'User'), params.id])
            redirect(action: "show", id: params.id)
        }
    }
}
